/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.message.impl;

import cn.easyplatform.spi.listener.ApplicationListener;
import cn.easyplatform.spi.listener.event.AppEvent;
import cn.easyplatform.type.JmsObject;
import cn.easyplatform.web.message.AbstractJmsConsumer;
import cn.easyplatform.web.message.entity.Destination;

import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import java.io.Serializable;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class JmsMessageConsumer extends AbstractJmsConsumer {

    private ApplicationListener applicationListener;

    public JmsMessageConsumer(ConnectionFactory connectionFactory, Destination dest, ApplicationListener applicationListener) {
        super(connectionFactory, dest);
        this.applicationListener = applicationListener;
    }

    @Override
    public void onMessage(Message message) {
        if (message instanceof ObjectMessage) {
            ObjectMessage msg = (ObjectMessage) message;
            try {
                Serializable data = msg.getObject();
                if (data instanceof AppEvent) {
                    AppEvent evt = (AppEvent) data;
                    data = new AppEvent(evt.getName(), new JmsObject(msg.getJMSMessageID(), msg.getJMSTimestamp(), destination.getTimeToLive(), evt.getData()));
                } else
                    data = new AppEvent(this.destination.getName(), new JmsObject(msg.getJMSMessageID(), msg.getJMSTimestamp(), destination.getTimeToLive(), msg.getObject()));
                applicationListener.publish(msg.getStringProperty("pid"), destination.getName(), data, msg.getStringProperty("uid"));
                if (this.destination.getAcknowledge() != Session.AUTO_ACKNOWLEDGE)
                    message.acknowledge();
            } catch (Exception e) {
                if (log.isErrorEnabled())
                    log.error("onMessage", e);
            }
        }
    }
}
